package org.space.ai.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.galaxy.common.mybatis.core.page.TableDataInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.space.ai.config.AiConfig;
import org.space.ai.domain.ProductBo;
import org.space.ai.domain.ProductVo;
import org.space.ai.feign.ProductFeignClient;
import org.space.ai.service.AiService;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class AiServiceImpl implements AiService {
    private final AiConfig aiConfig;
    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;
    private final ProductFeignClient productFeignClient;

    @Override
    public Map<String, Object> checkForbiddenWords(String text) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + aiConfig.getApiKey());

            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "glm-4-plus");

            List<Map<String, String>> messages = new ArrayList<>();
            Map<String, String> systemMessage = new HashMap<>();
            systemMessage.put("role", "system");
            systemMessage.put("content", "你是一个专业的文本审核助手，负责检查文本中是否包含违规内容。如果内容没有违规，请直接返回\"无违规\"。");

            Map<String, String> userMessage = new HashMap<>();
            userMessage.put("role", "user");
            userMessage.put("content", String.format("请分析以下评价内容是否包含违规词语，包括但不限于：政治敏感、色情、暴力、广告、辱骂等。如果包含，请列出具体的违规词语并说明原因。\n" +
                    "评价内容：%s\n" +
                    "请按以下格式返回：\n" +
                    "违规词语：xxx,xxx\n" +
                    "违规原因：xxx\n" +
                    "如果内容没有违规，请直接返回\"无违规\"。", text));

            messages.add(systemMessage);
            messages.add(userMessage);
            requestBody.put("messages", messages);
            requestBody.put("temperature", 0.7);
            requestBody.put("top_p", 0.7);

            HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
            Map<String, Object> response = restTemplate.postForObject(aiConfig.getApiUrl(), request, Map.class);

            if (response != null && response.containsKey("choices")) {
                List<Map<String, Object>> choices = (List<Map<String, Object>>) response.get("choices");
                if (!choices.isEmpty()) {
                    Map<String, Object> choice = choices.get(0);
                    Map<String, String> message = (Map<String, String>) choice.get("message");
                    String content = message.get("content");

                    if (content.contains("无违规")) {
                        return Map.of("words", Collections.emptyList(), "reason", "");
                    }

                    String[] lines = content.split("\n");
                    List<String> words = new ArrayList<>();
                    String reason = "";

                    for (String line : lines) {
                        if (line.startsWith("违规词语：")) {
                            String[] wordArray = line.substring(5).split(",");
                            for (String word : wordArray) {
                                String trimmedWord = word.trim();
                                if (!trimmedWord.equals("无")) {
                                    words.add(trimmedWord);
                                }
                            }
                        } else if (line.startsWith("违规原因：")) {
                            reason = line.substring(5).trim();
                        }
                    }

                    return Map.of("words", words, "reason", reason);
                }
            }

            return Map.of("words", Collections.emptyList(), "reason", "");
        } catch (Exception e) {
            log.error("违规词检测失败", e);
            return Map.of("words", Collections.emptyList(), "reason", "");
        }
    }

    @Override
    public Map<String, String> getForbiddenWordCategories() {
        return Map.of(
            "political", "政治敏感",
            "pornographic", "色情",
            "violent", "暴力",
            "advertising", "广告",
            "other", "其他违规"
        );
    }

    @Override
    public Map<String, Object> recommendDrinks(double temperature, double humidity, String windSpeed, String windDirection, List<Map<String, Object>> products) {
        try {
            // 如果前端没有传商品数据，则从商品服务获取
            if (products == null || products.isEmpty()) {
                try {
                    TableDataInfo<ProductVo> productVoTableDataInfo = productFeignClient.listProducts(new ProductBo(), 1, 100);
                    List<ProductVo> productVos = productVoTableDataInfo.getRows();
                    products = productVos.stream()
                        .map(vo -> {
                            Map<String, Object> map = new HashMap<>();
                            map.put("id", vo.getId()); // 假设商品ID在ProductVo中可以通过getId()方法获取
                            map.put("name", vo.getName());
                            map.put("price", vo.getPrice());
                            map.put("description", vo.getName() + " - 售价: " + vo.getPrice());
                            return map;
                        })
                        .collect(Collectors.toList());
                    log.info("从商品服务获取到{}个商品", products.size());
                } catch (Exception e) {
                    log.error("获取商品列表失败", e);
                    return Map.of(
                        "reason", "获取商品列表失败，请稍后重试",
                        "recommendations", Collections.emptyList()
                    );
                }
            }

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + aiConfig.getApiKey());

            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "glm-4-plus");

            List<Map<String, String>> messages = new ArrayList<>();
            Map<String, String> systemMessage = new HashMap<>();
            systemMessage.put("role", "system");
            systemMessage.put("content", "你是一个专业的饮料推荐助手，根据天气情况和商品列表，为用户推荐合适的饮料。");

            // 构建商品列表字符串
            StringBuilder productsStr = new StringBuilder();
            for (Map<String, Object> product : products) {
                productsStr.append("商品ID：").append(product.get("id"))
                    .append("，商品名称：").append(product.get("name"))
                    .append("，价格：").append(product.get("price"))
                    .append("，描述：").append(product.get("description"))
                    .append("\n");
            }
            log.info("可选商品列表" + productsStr.toString());
            Map<String, String> userMessage = new HashMap<>();
            userMessage.put("role", "user");
            userMessage.put("content", String.format("请根据以下天气情况和商品列表，推荐3-5款最适合的饮料：\n" +
                    "温度：%.1f°C\n" +
                    "湿度：%.1f%%\n" +
                    "风速：%s\n" +
                    "风向：%s\n\n" +
                    "可选商品列表：\n%s\n" +
                    "请按以下格式返回：\n" +
                    "推荐理由：xxx\n" +
                    "推荐商品：\n" +
                    "1. 商品ID：xxx，商品名称：xxx（原因：xxx）\n" +
                    "2. 商品ID：xxx，商品名称：xxx（原因：xxx）\n" +
                    "3. 商品ID：xxx，商品名称：xxx（原因：xxx）",
                temperature, humidity, windSpeed, windDirection, productsStr.toString()));

            messages.add(systemMessage);
            messages.add(userMessage);
            requestBody.put("messages", messages);
            requestBody.put("temperature", 0.7);
            requestBody.put("top_p", 0.7);

            HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
            Map<String, Object> response = restTemplate.postForObject(aiConfig.getApiUrl(), request, Map.class);

            if (response != null && response.containsKey("choices")) {
                List<Map<String, Object>> choices = (List<Map<String, Object>>) response.get("choices");
                if (!choices.isEmpty()) {
                    Map<String, Object> choice = choices.get(0);
                    Map<String, String> message = (Map<String, String>) choice.get("message");
                    String content = message.get("content");

                    // 解析AI返回的推荐结果
                    String[] lines = content.split("\n");
                    String reason = "";
                    List<Map<String, String>> recommendations = new ArrayList<>();

                    for (String line : lines) {
                        if (line.startsWith("推荐理由：")) {
                            reason = line.substring(5).trim();
                        } else if (line.matches("\\d+\\. .*")) {
                            String[] parts = line.split("（原因：");
                            if (parts.length == 2) {
                                String[] productParts = parts[0].split("，商品名称：");
                                if (productParts.length == 2) {
                                    String productId = productParts[0].substring(productParts[0].indexOf("商品ID：") + 5).trim();
                                    String productName = productParts[1].trim();
                                    String productReason = parts[1].replace("）", "").trim();
                                    recommendations.add(Map.of(
                                        "id", productId,
                                        "name", productName,
                                        "reason", productReason
                                    ));
                                }
                            }
                        }
                    }

                    return Map.of(
                        "reason", reason,
                        "recommendations", recommendations
                    );
                }
            }

            return Map.of(
                "reason", "无法生成推荐",
                "recommendations", Collections.emptyList()
            );
        } catch (Exception e) {
            log.error("饮料推荐失败", e);
            return Map.of(
                "reason", "推荐失败，请稍后重试",
                "recommendations", Collections.emptyList()
            );
        }
    }

}
